'use strict';
const Controller = require('egg').Controller;
const WechatAPI = require('co-wechat-api');
const crypto = require('crypto');

const weChatOAuth = {
  appId: 'wxb365a1394f9bcce5',
  secret: '0f89262e8b7db8a92a76f2be0a3e7974',
  token: 'fgsitely',
};
const tokenCache = {
  access_token: '',
  updateTime: Date.now(),
  expires_in: 7200,
};
const api = new WechatAPI(
  weChatOAuth.appId,
  weChatOAuth.secret
);
class weChatOAuthController extends Controller {
  async index() {
    const query = this.ctx.request.query;
    const signature = query.signature;
    const timestamp = query.timestamp;
    const nonce = query.nonce;
    const echostr = query.echostr;
    console.log('===================', 1212);
    if (await this.check(timestamp, nonce, signature, weChatOAuth.token)) {
      this.ctx.body = echostr;
    } else {
      this.ctx.body = 'It is not from weixin';
    }
  }

  async check(timestamp, nonce, signature, token) {
    const tmp = [ token, timestamp, nonce ].sort().join('');
    const currSign = crypto.createHash('sha1').update(tmp).digest('hex');
    return (currSign === signature);
  }
  async getOAuth() {
    const {
      ctx,
    } = this;
    const param = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${weChatOAuth.appId}&secret=${weChatOAuth.secret}`;
    const res = await ctx.curl(param, {
      dataType: 'json',
    });
    Object.assign(tokenCache, res.data, {
      updateTime: Date.now(),
    });
    ctx.body = res.data;
  }
  async getFollowers() {
    const {
      ctx,
    } = this;
    const url = `https://api.weixin.qq.com/cgi-bin/user/get?access_token=${tokenCache.access_token}`;
    const res = await ctx.curl(url, {
      dataType: 'json',
    });
    ctx.session.openid = await res.data.data.openid[0];
    ctx.body = res.data;
  }
  async getInfo() {
    const {
      ctx,
    } = this;
    const res = await api.getUser({
      openid: ctx.session.openid,
      lang: 'en',
    });
    console.log(await api.getTags());
    // res = await api.batchGetUsers(res.data.openid, 'zh_CN')
    ctx.body = res;
  }
}

module.exports = weChatOAuthController;
